import React, { useState, useEffect, useContext } from "react";
import { GlobalContext } from "./index.js";
import { Form, Input, Row, Col, Radio, Table, Modal, Tabs,Popconfirm,Typography } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { getAuthList, addAuth } from "../../api/auth/index";
//输入框分离高度
const styles = { marginTop: "20px", width: "100%", textAlign: "center" };
const AuthList = getAuthList();
const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `输入 ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
export default function Tabpane() {
  const { isModalVisible, setIsModalVisible } = useContext(GlobalContext);
  const [form] = Form.useForm();
  const [data, setData] = useState([
    ...AuthList[AuthList.findIndex((c) => c.id === "ceshi")].actions,
  ]);
  
  
  const onChangeForm = (e) => {};
  const onClickDelete = (record) => {
    data.splice(data.findIndex((c) => c.action === record.action), 1);
    setData([...data]);
  };
  const [editingaction, setEditingaction] = useState('');

  const isEditing = (record) => record.action === editingaction;

  const edit = (record) => {
    form.setFieldsValue({
      action: '',
      name: '',
      describe: '',
      ...record,
    });
    setEditingaction(record.action);
  };

  const cancel = () => {
    setEditingaction('');
  };
  const save = async (action) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => action === item.action);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingaction('');
      } else {
        newData.push(row);
        setData(newData);
        setEditingaction('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const columns = [
    {
        title: '操作类型',
        dataIndex: 'action',
        width: '25%',
        editable: true,
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: '15%',
        editable: true,
      },
      {
        title: '描述',
        dataIndex: 'describe',
        width: '40%',
        editable: true,
      },
    {
      title: <div>操作 | {<PlusOutlined />}</div>,
      dataIndex: "operate",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.action)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="确定取消？" onConfirm={cancel} okText="确定" cancelText="取消">
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <div>
          <Typography.Link disabled={editingaction !== ''} onClick={() => edit(record)}>
            编辑 
          </Typography.Link>
          <span> | </span>
          <Typography.Link disabled={editingaction !== ''} onClick={() => onClickDelete(record)}>
            删除
          </Typography.Link>
          </div>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  //添加权限，点击确定
  const handleOk = (e) => {
    //表单校验
    e.validateFields();
    if (
      e.getFieldsValue().purviewID &&
      e.getFieldsValue().purviewName &&
      e.getFieldsValue().condition !== undefined
    ) {
      let auth = [];
      auth = [
        {
          id: e.getFieldsValue().purviewID,
          name: e.getFieldsValue().purviewName,
          status: e.getFieldsValue().condition ? 1 : 0,
          actions: [...data],
        },
      ];
      addAuth(...auth);
      setIsModalVisible(false);
      form.resetFields();
      setData([
        ...AuthList[AuthList.findIndex((c) => c.id === "ceshi")].actions,
      ]);
    }
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    setData([
      ...AuthList[AuthList.findIndex((c) => c.id === "ceshi")].actions,
    ]);
    form.resetFields();
  };
  //新增模块
  //新增-标签页
  const { TabPane } = Tabs;

//   function callback(action) {
//     console.log("111" + action);
//   }

  return (
    <Modal
      title="新建权限"
      visible={isModalVisible}
      onOk={() => handleOk(form)}
      onCancel={handleCancel}
      okText="确定"
      cancelText="取消"
      width={1000}
    >
      <div>
        <Tabs defaultActiveaction="1">
          <TabPane tab="基本信息" action="1">
            <div>
              <Row>
                <Form
                  form={form}
                  layout="inline"
                  requiredMark={true}
                  onValuesChange={() => onChangeForm(form)}
                  style={styles}
                >
                  <Col span={9} offset={3}>
                    <Form.Item
                      label="权限标识(ID):"
                      style={styles}
                      name="purviewID"
                      rules={[
                        {
                          required: true,
                          message: "请输入权限标识符",
                        },
                      ]}
                    >
                      <Input placeholder="只能由字母数字下划线组成" />
                    </Form.Item>
                  </Col>
                  <Col span={9}>
                    <Form.Item
                      label="权限名称:"
                      style={styles}
                      name="purviewName"
                      rules={[
                        {
                          required: true,
                          message: "请输入权限标名称",
                        },
                      ]}
                    >
                      <Input />
                    </Form.Item>
                  </Col>
                  <Col span={9} offset={3}>
                    <Form.Item
                      label="状态:"
                      style={styles}
                      name="condition"
                      rules={[
                        {
                          required: true,
                          message: "请选择状态",
                        },
                      ]}
                    >
                      <Radio.Group buttonStyle="solid">
                        <Radio.Button value={true}>启用</Radio.Button>
                        <Radio.Button value={false}>禁用</Radio.Button>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    {/* <Table
                      name="permission"
                      columns={columns}
                      dataSource={data}
                      pagination={false}
                      style={styles}
                      rowKey="name"
                      title={() => "操作配置"}
                    /> */}
                    <Table
                      components={{
                        body: {
                          cell: EditableCell,
                        },
                      }}
                      bordered
                      dataSource={data}
                      columns={mergedColumns}
                      rowClassName="editable-row"
                      pagination={{
                        onChange: cancel,
                      }}
                    />
                  </Col>
                </Form>
              </Row>
            </div>
          </TabPane>
        </Tabs>
      </div>
    </Modal>
  );
}
